const path = require('path');
const db = require('./index.js');
const Mongoose = require('mongoose');
const md5 = require('../util.js').md5;
const logSchema = new Mongoose.Schema({
    username: String,
    password: String,
    signUpData: {
        type: Date
    },
    upDate: {
        type: Date,
        default: Date.now()
    },
    token: String,
    tokenLossTime: Number
});

const logTable = db.model('logMsg', logSchema);

function findInUsername(name) {
    return new Promise((s, f) => {
        logTable.findOne({ username: name }, (err, res) => {
            if (err) {
                log.error('查询用户名是否重复时, 出错');
                console.error(err);
                return s('400');
            }
            log.debug('查询用户名', res ? '存在重复' : '不存在重复');
            let type = res ? '200' : '0'
            return s(type);
        })
    })
}

async function addUser(data = {}) {
    if (!data.username || !data.pwd) {
        log.debug('增加用户失败, 缺少必要参数')
        return '400';
    }
    let isAgainUser = await findInUsername(data.username);
    if (isAgainUser !== '0') return isAgainUser;
    return new Promise((s, f) => {
        let pwd = md5(data.pwd);
        logTable.create({
            username: data.username,
            password: pwd,
            signUpData: Date.now()
        }, (err) => {
            if (err) {
                log.error('增加用户失败, 数据库报错');
                console.error(err);
                return f('400');
            }
            log.debug('增加成功');
            return s('0');
        })
    })
}

function findInNameAndPwd(data) {
    if (!data.username || !data.pwd) {
        log.debug('用户登录查询, 缺少参数')
        return '400';
    }
    return new Promise((s, f) => {
        let pwd = md5(data.pwd);
        logTable.findOne({ username: data.username, password: pwd }, { username: 1, password: 1, _id: 0 }, (err, res) => {
            if (err) {
                log.error('用户登录查询, 出错');
                console.error(err);
                return s('400');
            }
            log.debug('用户登录查询', res ? '成功' : '失败');
            let type;
            if (res) {
                let token = md5(Date.now().toString(16));
                log.debug(`设置的token ${token}`)
                upDataToken(res, token, (types) => {
                    log.debug('更新token的状态', types);
                    if (types === '0') {
                        type = {
                            type: '0',
                            token: token
                        }
                    } else {
                        type = types;
                    }
                    return s(type);
                });
            } else {
                return s('200');
            }
        })
    })
}

function upDataToken(data, token, callback) {
    if (!data.password || !data.username || !token) {
        log.error('更新token, 缺少参数');
        return callback('400');
    }
    let time = Date.now() + 120000;//86400000;
    logTable.update(data, { $set: { token, tokenLossTime: time } }, (err, res) => {
        if (err) {
            log.error('更新token, 数据库报错');
            console.error(err);
            return callback('400')
        }
        return callback('0')
    });
}

function findIntoken(data) {
    if (!data) {
        log.error('查询token 缺少参数');
        return '400';
    }
    return new Promise((s, f) => {
            logTable.findOne({ token: data }, { tokenLossTime: 1 }, (err, res) => {
                    if (err) {
                        log.error('查询token 数据库报错');
                        console.error(err);
                        return s('400');
                    }
                    log.debug('查询token成功');
                    let type = res && res.tokenLossTime && (Date.now() < res.tokenLossTime) ? '0' : '200';
                        return s(type);
                    })
            })
    }
    module.exports = {
        addUser,
        findInNameAndPwd,
        findIntoken
    }